package com.ruixin.mvc.util;

import com.ruixin.base.util.StringUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 路径工具类
 */
public class PathUtil {

    /**
     * path 匹配
     * @param urlPath
     * @param path
     * @return
     */
    public static boolean match(String urlPath,String path){
        if(urlPath.equals(path)){
            return true;
        }
        String[] urls = urlPath.split("/");
        String[] paths = path.split("/");
        if(urls.length == paths.length){
            for (int i = 0; i < urls.length; i++) {
                if(!(urls[i].equals(paths[i])||"*".equals(paths[i])||isArg(paths[i]))){
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    /**
     * 是否是路径参数
     * @param path
     * @return
     */
    public static boolean isArg(String path){
        String regex = "\\$\\{(.*?)}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(path);
        return matcher.find();
    }

    /**
     * path 匹配
     * @param urlPath
     * @param prefix
     * @param path
     * @return
     */
    public static boolean match(String urlPath,String prefix,String path){
        path = getPath(prefix, path);
        return match(urlPath,path);
    }

    /**
     * path 合并
     * @param prefix
     * @param path
     * @return
     */
    public static String getPath(String prefix,String path){
        if(StringUtil.isBlackOrNull(prefix)){
            return formatPath(File.separator+path);
        }
        return formatPath(File.separator + prefix+File.separator+path);
    }

    /**
     * 格式化路径
     * @param path
     * @return
     */
    public static String formatPath(String path){
        if(StringUtil.isBlackOrNull(path)){
            return "/";
        }
        path = path.replace("\\","/");
        path = path.replace("//","/");
        if(!path.startsWith("/")){
            path = "/"+path;
        }
        return path;
    }

    /**
     * 获取连接参数
     * @param urlPath
     * @param path
     * @return
     */
    public static Map<String,String> getPathVariable(String urlPath,String path){
        Map<String,String> pathVariables = new HashMap<>();
        String[] urls = urlPath.split("/");
        String[] paths = path.split("/");
        for (int i = 0; i < urls.length; i++) {
            if(!(urls[i].equals(paths[i])||"*".equals(paths[i]))&&isArg(paths[i])){
                String regex = "\\$\\{(.*?)}";
                Pattern pattern = Pattern.compile(regex);
                Matcher matcher = pattern.matcher(paths[i]);
                if(matcher.find()){
                    String name = matcher.group(1);
                    pathVariables.put(name,urls[i]);
                }
            }
        }
        return pathVariables;
    }
}
